package com.example.demo.oss;

import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Response;

import java.util.TreeMap;

/**
 * @author: yby
 * @desc: 获取临时上传的key id
 * @date: 2024/9/20 13:58
 */
// 根据 github 提供的 maven 集成方法导入 java sts sdk，使用 3.1.1 及更高版本
public class TxOssUtil {
    public static void main(String[] args) {
        TreeMap<String, Object> config = new TreeMap<String, Object>();
        String region = "ap-beijing";
        String secretId = "AKID0xnXNBd1JVWN9uU9iDYhjgjfOG1ZzbIn";
        String secretKey = "UnwPjx32ucIrKlRFxXzZ1a3Mcn5EA0fB";
        String bucket = "q4-record-1300314960";

        try {
//            Properties properties = new Properties();
//            File configFile = new File("local.properties");
//            properties.load(new FileInputStream(configFile));

            // 云 api 密钥 SecretId
            config.put("secretId", secretId);
            // 云 api 密钥 SecretKey
            config.put("secretKey", secretKey);

//            if (properties.containsKey("https.proxyHost")) {
//                System.setProperty("https.proxyHost", properties.getProperty("https.proxyHost"));
//                System.setProperty("https.proxyPort", properties.getProperty("https.proxyPort"));
//            }

            // 设置域名,可通过此方式设置内网域名
            //config.put("host", "sts.internal.tencentcloudapi.com");

            // 临时密钥有效时长，单位是秒
            config.put("durationSeconds", 1800);

            // 换成你的 bucket
            config.put("bucket", bucket);
            // 换成 bucket 所在地区
            config.put("region", region);

            // 可以通过 allowPrefixes 指定前缀数组, 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            config.put("allowPrefixes", new String[] {
                    "*",
            });

            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            String[] allowActions = new String[] {
                    // 简单上传
                    "name/cos:PutObject",
                    "name/cos:PostObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload"
            };
            config.put("allowActions", allowActions);

            Response response = CosStsClient.getCredential(config);
            System.out.println(response.credentials.tmpSecretId);
            System.out.println(response.credentials.tmpSecretKey);
            System.out.println(response.credentials.sessionToken);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("no valid secret !");
        }
    }
}